'use strict';

const {Controller} = require('egg');

class WbUrlController extends Controller {
    async index() {
        const {ctx} = this;
        const {query, model, service, helper} = ctx;
        const options = {
            limit: helper.parseInt(query.limit),
            offset: helper.parseInt(query.offset),
        };

        const data = await ctx.service.wbUrl.list(options);
        ctx.body = {
            code: 0,
            data: {
                count: data.count,
                items: data.rows,
            },
        };
    }

    // 查找微博人
    async selectName() {
        const {ctx, app} = this;
        const {query} = ctx;
        let name = query.name; // 微博昵称
        let url = 'https://m.weibo.cn/api/container/getIndex?containerid=100103type%3D3%26q%3D' + name + '%26t%3D0&page_type=searchall';
        let result;
        if (await app.redis.get(`search:${name}`)) {
            result = JSON.parse(await app.redis.get(`search:${name}`))
        } else {
            result = await ctx.curl(url, {
                    dataType: 'json',
                    method: 'get',
                }
            );
            await app.redis.set(`search:${name}`, JSON.stringify(result))
        }
        ctx.body = {
            code: 0,
            data: {
                cardlistInfo: result.data.data.cardlistInfo,
                cards: result.data.data.cards,
            }
        };
    }

    async create() {
        const {ctx} = this;
        const {service} = ctx;
        let transaction;
        try {
            // 这里需要注意，egg-sequelize会将sequelize实例作为app.model对象
            transaction = await ctx.model.transaction();
            const body = ctx.request.body;
            let params = [];
            body.forEach((item, index) => {
                params.push({
                    screen_name: item.user.screen_name,
                    wb_uid: item.user.id,
                    profile_image_url: item.user.profile_image_url,
                    profile_url: item.user.profile_url
                });
            });
            const createData = await service.wbUrl.create(params);
            ctx.status = 201;
            ctx.body = {
                code: 0,
                data: createData,
            };
        } catch (err) {
            ctx.logger.error(err);
            await transaction.rollback()
        }
    }

    async update() {
        const {ctx} = this;
        const {params, service, helper} = ctx;
        const body = ctx.request.body;
        const id = helper.parseInt(body.id);
        const res = await service.wbUrl.update({
            id,
            updates: body,
        });
        ctx.body = {
            code: 0,
            data: res,
        };
    }

    async destroy() {
        const {ctx} = this;
        const {params, service, helper} = ctx;
        const id = helper.parseInt(params.id);
        await service.wbUrl.destroy(id);
        ctx.status = 200;
        ctx.body = {
            code: 0,
            success: true,
        };
    }

    async wbList() {
        const {ctx, app} = this;
        let url = "http://q236658q46.iask.in/weibo/list?name=%E5%88%98%E6%8A%B1";
        let result;
        if (await app.redis.get('刘抱:wbList')) {
            result = JSON.parse(await app.redis.get('刘抱:wbList'))
        } else {
            result = await ctx.curl(url, {
                dataType: 'json',
                method: 'get'
            });
            await app.redis.set('刘抱:wbList', JSON.stringify(result))
        }
        ctx.body = result.data
    }

    async wbSend() {
        const {ctx, app} = this;
        let url = 'https://api.weibo.cn/2/statuses/send';
        try {
            const result = await ctx.curl(url, {
                method: 'POST',
                data: {
                    'c': 'weixinminiprogram',
                    's': 'b2b3d422',
                    'from': '1885396040',
                    'wm': '90163_90001',
                    'lang': 'zh_CN',
                    'new_version': '0',
                    'gsid': '_2A_p8UnB8CoX0ky8nkQjfSlUE3cPlPcwqXf62zmFeEtLG8oFeQ6ghWFSEeNA2oV_9FCtNzoS3tJetaRr4iayr2fT1',
                    'uid': '2414607967',
                    'content': ctx.request.body.content,
                    'pic_id': '',
                    'uicode': '30000306',
                    'ext': 'wbvid:1011569628995|uicode:30000359|luicode:10000360|lfid:miniprogram',
                },
                dataType: 'json',
            });
            if (!result.errmsg) {
                await app.redis.del('刘抱:wbList')
            }
            ctx.status = 200;
            ctx.body = {
                code: 0,
                success: true,
                data: result
            };
        } catch (e) {
            ctx.body = {
                code: 403,
                message: 'Authing auth failed',
                error: e,
            }
        }

    }
}

module.exports = WbUrlController;
